﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class MethodImplementationRule : ILRule<MethodImplementationHandle>
    {
        [ILInfo(true, ILInfoParseMethod.AsEntityHandle)]
        public TypeDefinitionHandle Type { get; }

        [ILInfo(true)]
        public EntityHandle MethodBody { get; }

        [ILInfo(true)]
        public EntityHandle MethodDeclaration { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public MethodImplementationRule(
            TypeDefinitionHandle type,
            EntityHandle methodBody,
            EntityHandle methodDeclaration)
            : base()
        {
            Type = type;
            MethodBody = methodBody;
            MethodDeclaration = methodDeclaration;
        }

        public MethodImplementationRule(MetadataReader reader, MethodImplementationHandle methodImplementationHandle)
            : base(reader)
        {
            MethodImplementation methodImplementation = reader.GetMethodImplementation(methodImplementationHandle);
            Type = methodImplementation.Type;
            MethodBody = methodImplementation.MethodBody;
            MethodDeclaration = methodImplementation.MethodDeclaration;
            CustomAttributes = methodImplementation.GetCustomAttributes();
        }

        public override MethodImplementationHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddMethodImplementation(
                type: Type,
                methodBody: MethodBody,
                methodDeclaration: MethodDeclaration);
        }
    }
}